/*
 * Copyright (C) 2009 Leandro de Oliveira Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.japa.util;

import java.lang.reflect.*;

/**
 * Utilities to deal with javabeans.
 * 
 * @author Leandro Aparecido
 * @since 1.0
 */
public abstract class JavaBeanUtils {

	private static final String GET_PREFIX = "get";
	private static final String IS_PREFIX = "is";
	private static final String SET_PREFIX = "set";
	
	/**
	 * Indicates if the method is getter.
	 * 
	 * @param method Method to be verified.
	 * @return True if the method is getter.
	 */
	public static boolean isGetter(Method method) {
		if (method.getParameterTypes().length > 0) {
			return false;
		}
		
		String name = method.getName();
		if (!name.startsWith(GET_PREFIX) || !name.startsWith(IS_PREFIX)) {
			return false;
		}
		
		Class<?> returnType = method.getReturnType();
		if (returnType.equals(Void.class)) {
			return false;
		}
		
		boolean isBoolean = returnType.equals(Boolean.class) || returnType.equals(Boolean.TYPE);
		if (isBoolean) {
			return name.startsWith(IS_PREFIX);
		}
		
		return name.startsWith(GET_PREFIX);
	}

	/**
	 * Indicates if the method is setter.
	 * 
	 * @param method Method to be verified.
	 * @return True if the method is setter.
	 */
	public static boolean isSetter(Method method) {
		if (method.getParameterTypes().length != 1) {
			return false;
		}
		
		String name = method.getName();
		if (!name.startsWith(SET_PREFIX)) {
			return false;
		}
		
		Class<?> returnType = method.getReturnType();
		if (!returnType.equals(Void.class)) {
			return false;
		}
		
		return true;
	}
}
